package bsc.war.form;

import bsc.war.delegate.DelegateBSC;
import bsc.war.factory.Factory;
import bsc.war.handler.UserDomain;
import bsc.war.service.ScoreCardUtils;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author castrosalazar
 */
public class UpdateSession extends AbstractController {

    public UpdateSession() {
    }

    @Override
    protected ModelAndView handleRequestInternal(
            HttpServletRequest request,
            HttpServletResponse response)
            throws Exception {
        String redirect = null;
        DelegateBSC delegate = (DelegateBSC) Factory.getBean("DelegateBSC");
        try {
            redirect = request.getParameter("location");
            if (request.getParameter("date") != null) {
                Integer tmpDate[] = new Integer[3];
                StringTokenizer dateTokens = new StringTokenizer(request.getParameter("date"), "/");
                for (int i = 0; i < 3; i++) {
                    tmpDate[i] = Integer.parseInt(dateTokens.nextToken());
                }
                /*int lastDayOfMonth;
                switch(tmpDate[1])
                {
                case 1: case 3: case 5: case 7: case 8: case 10: case 12:
                lastDayOfMonth = 31; break;
                case 2:
                if( new GregorianCalendar().isLeapYear(tmpDate[2]) )
                lastDayOfMonth = 30;
                else lastDayOfMonth = 28;
                break;
                default:
                lastDayOfMonth = 30;
                break;
                }*/
                request.getSession().setAttribute("date", ScoreCardUtils.generateDate(/*lastDayOfMonth*/tmpDate[0], tmpDate[1], tmpDate[2]));
            }
            if (request.getParameter("comparation") != null) {
                request.getSession().setAttribute("comparation", delegate.findComparation(Long.parseLong(request.getParameter("comparation"))));
            }
            if(request.getParameter("scoreDomain") != null) {
                UserDomain.processRequestInternal(request, response, delegate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Catched exception", e);
        }
        return new ModelAndView(new RedirectView(redirect == null ? request.getContextPath() + "/mapFinalUser.do" : request.getContextPath() + '/' + redirect));
    }
}
